<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="部门名称" name="deptId">
          <t-cascader
            v-model:value="params.deptId"
            :options="simpleDeptTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
            check-strictly
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="组名称" name="name">
          <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="messageGroupCRUD.page"
      column-controller-key="messageGroupList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button v-permission="['system:message-group-config:create']" @click="handleOpenDialog('create', {})">
            新建组
          </t-button>
        </div>
      </template>
      <template #parentId="{ row }">
        {{ simpleDeptList.find((item) => item.id === row.parentId)?.name }}
      </template>
      <template #deptId="{ row }">
        {{ simpleDeptList.find((item) => item.id === row.deptId)?.name }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:message-group-config:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['system:message-group-config:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:message-group-config:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="messageGroupCRUD"
      header="*组"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="父级部门" name="parentId" :rules="[{ required: true, message: '请选择父级部门' }]">
        <t-cascader
          v-model:value="formData.parentId"
          :options="simpleDeptTree"
          :keys="{ value: 'id', label: 'name' }"
          placeholder="请选择父级部门"
          filterable
          clearable
          check-strictly
          disabled
        />
      </t-form-item>
      <t-form-item label="部门名称" name="deptId" :rules="[{ required: true, message: '请选择部门名称' }]">
        <t-cascader
          v-model:value="formData.deptId"
          :options="simpleDeptTree"
          :keys="{ value: 'id', label: 'name' }"
          placeholder="请选择部门名称"
          filterable
          clearable
          :readonly="readonly"
          check-strictly
          @change="
            (value, context) => {
              if (value) {
                const parentId = context.node.data.parentId;
                formData.parentId = parentId;
              } else {
                formData.parentId = undefined;
              }
            }
          "
        />
      </t-form-item>
      <t-form-item label="组名称" name="name" :rules="[{ required: true, message: '请输入组名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入组名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="显示顺序" name="sort" :rules="[{ required: true, message: '请输入显示顺序' }]">
        <t-input-number
          v-model:value="formData.sort"
          :decimal-places="0"
          min="0"
          :allow-input-over-limit="false"
          placeholder="请输入显示顺序"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'MessageGroup',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef } from 'vue';

import { messageGroupCRUD } from '@/api/config/message-group';
import { getSimpleDeptList } from '@/api/system/dept';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import listToTree from '@/utils/listToTree';

// 精简部门列表
const simpleDeptList = ref([]);
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList().then((data) => {
    simpleDeptList.value = data;
    simpleDeptTree.value = listToTree(data);
  });
};
handleGetSimpleDeptTree();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '组ID' },
  { colKey: 'parentId', title: '父级部门' },
  { colKey: 'deptId', title: '部门名称' },
  { colKey: 'name', title: '组名称' },
  { colKey: 'sort', title: '显示顺序' },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 150 },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  messageGroupCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
</script>
